package com.mybatis.demo.plugin;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 插件方式1
 */
public class MyProxy1 {
  /**
   * 创建代理对象方法
   */
  public static Object wrap(Object target) {
    return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new HWInvocationHandler(target));
  }

  /**
   * 自定义代理类执行方法
   */
  static class HWInvocationHandler implements InvocationHandler {
    //目标类
    private Object target;

    public HWInvocationHandler(Object target) {
      this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(target, args);
      }
      System.out.println("------插入前置通知代码-------------");
      Object obj = method.invoke(target, args);
      System.out.println("------插入后置处理代码-------------");
      return obj;
    }
  }

  /**
   * 接口
   */
  public interface HelloService {
    void sayHello();
  }

  /**
   * 实现类
   */
  static class HelloServiceImpl implements HelloService {
    @Override
    public void sayHello() {
      System.out.println("sayHello......");
    }
  }

  public static void main(String[] args) {
    HelloServiceImpl helloService = new HelloServiceImpl();
    HelloService wrap = (HelloService) MyProxy1.wrap(helloService);
    wrap.sayHello();
  }
}
